package org.com.lcuiot.security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * 非对称加密
 * @author gaoge
 * @since 2022/11/23 11:07
 */
public  class AsymmetricEncrypt {
    private static Base64Crypto Base64 = new Base64Crypto();

    public static AsymmetricKeyPair generateKeyPair(int size) throws NoSuchAlgorithmException {
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
        keyGenerator.initialize(size, new SecureRandom());
        KeyPair keyPair = keyGenerator.generateKeyPair();
        PrivateKey priKey = keyPair.getPrivate();
        PublicKey pubKey = keyPair.getPublic();
        String privateKey = Base64.encodeToString(priKey.getEncoded());
        String publicKey = Base64.encodeToString(pubKey.getEncoded());
        return AsymmetricKeyPair.create(privateKey, publicKey);
    }

    public static byte[] encrypt(byte[] src, String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        byte[] encodedKey = Base64.decode(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(src);
    }

    public static byte[] decrypt(byte[] src, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        byte[] encodedKey = Base64.decode(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(src);
    }

}
